﻿using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AEM.Data.Enum;
using AEM.Utils;
using Microsoft.Win32;
using Actions = AEM.Data.BLL.Actions;
using System.Collections.Generic;
using AEM.Data;
using System.Linq;
using System.Windows.Documents;

namespace AEM.Basic
{
    /// <summary>
    /// Interaction logic for LiftState.xaml
    /// </summary>
    public partial class LiftStatusPoints : Window
    {
        public LiftStatusPoints()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(LiftStatusPoints_Loaded);
            this.TitleBar.MouseLeftButtonDown += new MouseButtonEventHandler(LiftStatusPoints_MouseLeftButtonDown);
            this.statusPointsList.SelectionChanged += new SelectionChangedEventHandler(statusList_SelectionChanged);
            this.typeLibList.SelectionChanged += new SelectionChangedEventHandler(typeLibList_SelectionChanged);

            this.statusAdd.Click += new RoutedEventHandler(statusAdd_Click);
            this.statusEdit.Click += new RoutedEventHandler(statusEdit_Click);
            this.statusDelete.Click += new RoutedEventHandler(statusDelete_Click);

            this.statusPointsImport.Click += new RoutedEventHandler(statusPointsImport_Click);
            this.statusPointsAdd.Click += new RoutedEventHandler(statusPointsAdd_Click);
            this.statusPointsEdit.Click += new RoutedEventHandler(statusPointsEdit_Click);
            this.statusPointsDelete.Click += new RoutedEventHandler(statusPointsDelete_Click);

            this.checkBox1.Checked += new System.Windows.RoutedEventHandler(checkBox_CheckedChanged);
            this.checkBox1.Unchecked += new System.Windows.RoutedEventHandler(checkBox_CheckedChanged);
        }

        void checkBox_CheckedChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.checkBox1.IsChecked.Value)
                this.statusPointsList.SelectAll();
            else
                this.statusPointsList.UnselectAll();
        }

        void LiftStatusPoints_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void sys_button_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        void LiftStatusPoints_Loaded(object sender, RoutedEventArgs e)
        {
            this.statusName.ItemsSource = Config.StatusList;
            this.statusName.DisplayMemberPath = "LiftStatusName";
            this.statusName.SelectedValuePath = "LiftStatusNum";
            //ListStatusPoints();
            this.typeLibList.ItemsSource = Config.TypeLibList;
            //liftType.ItemsSource = StringHelper.EnumToList<LiftType>();
            //liftType.SelectedIndex = 0;
        }

        private void ListStatusPoints(int[] typeids)
        {
            List<StatusPointsItem> list = (from Data.Model.StatusPoints sp in Config.StatusPointsList
                                           join Data.Model.LiftStatus ls in Config.StatusList// listStatus
                                           on sp.LiftStatusNum equals ls.LiftStatusNum
                                           where typeids.Contains(sp.ID)
                                           orderby sp.ID
                                           select new StatusPointsItem
                                           {
                                               ID = sp.ID,
                                               Byte = sp.StatusByte,
                                               Bit = sp.StatusBit,
                                               StatusNum = sp.LiftStatusNum,
                                               StatusName = ls.LiftStatusName
                                           }).ToList();
            this.statusPointsList.ItemsSource = list;
            foreach (StatusPointsItem i in this.statusPointsList.Items)
            {
                if (Array.Exists(typeids, x => x == i.ID))// i.ID == Convert.ToInt32(id))
                {
                    this.statusPointsList.SelectedItems.Add(i);
                }
            }
        }

        void statusList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.statusPointsList.SelectedItems.Count > 1) return;
            StatusPointsItem row = (sender as ListView).SelectedItem as StatusPointsItem;
            if (null == row) return;
            statusByte.Tag = row.ID;
            statusByte.Text = row.Byte;
            statusBit.Text = row.Bit;
            statusName.SelectedValue = row.StatusNum;
        }

        void typeLibList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Data.Model.TypeLib row = (sender as ListView).SelectedItem as Data.Model.TypeLib;
            if (null == row) return;
            typeLibNum.Text = row.TypeLibNum;
            liftType.SelectedIndex = row.LiftType;
            floorFormat.SelectedIndex = row.FloorFormat;
            int[] ids = row.StatusPoints.toIntArray();

            //changed by lynx.kor on 2013/06/12 23:20 for list typelib's points to the pointslistview by new tactics;
            ListStatusPoints(ids);

            //this.statusPointsList.SelectedItems.Clear();
            //foreach (string id in ids)
            //{
            //foreach (StatusPointsItem i in this.statusPointsList.Items)
            //{
            //    if (Array.Exists(ids, x => x == i.ID.ToString()))// i.ID == Convert.ToInt32(id))
            //    {
            //        this.statusPointsList.SelectedItems.Add(i);
            //    }
            //}
            //}
            //changed end
        }

        void statusAdd_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (string.IsNullOrEmpty(statusByte.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusByte") as string); return; }
            if (string.IsNullOrEmpty(statusBit.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusBit") as string); return; }
            if (string.IsNullOrEmpty(statusName.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusName") as string); return; }
            if (!statusByte.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("StatusByte") as string); return; }
            if (!statusBit.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("StatusBit") as string); return; }
            Data.Model.StatusPoints row = new Data.Model.StatusPoints();
            row.StatusByte = statusByte.Text.Trim();
            row.StatusBit = statusBit.Text.Trim();
            row.LiftStatusNum = Convert.ToInt32(statusName.SelectedValue);

            Actions.StatusPoints.AddStatusPointsResult ret = Actions.StatusPoints.AddStatusPoints(row);
            switch (ret)
            {
                case Actions.StatusPoints.AddStatusPointsResult.StatusPointsIsNull:
                    errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
                    break;
                case Actions.StatusPoints.AddStatusPointsResult.StatusPointsIsExist:
                    errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
                    break;
                case Actions.StatusPoints.AddStatusPointsResult.Ok:
                    errmsg.Text = this.TryFindResource("successfuladd") as string;
                    Config.StatusPointsList = Data.DAL.StatusPoints.List("");
                    //ListStatusPoints();
                    statusByte.Text = "";
                    statusBit.Text = "";
                    statusName.Text = "";
                    break;
            }
            row = Actions.StatusPoints.SelectStatusPoints(row.StatusByte, row.StatusBit, row.LiftStatusNum);

            if (null != row)
            {
                if (string.IsNullOrEmpty(typeLibNum.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("TypeLibNum") as string); return; }
                if (!typeLibNum.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("TypeLibNum") as string); return; }
                Data.Model.TypeLib tl = Actions.StatusPoints.SelectTypeLib(typeLibNum.Text.Trim());

                if (null != tl)
                {
                    List<int> ids = tl.StatusPoints.toIntArray().ToList();
                    ids.Add(row.ID);
                    int[] points = ids.Distinct().ToArray();
                    Array.Sort(points);
                    tl.StatusPoints = points.Join(",");
                    Actions.StatusPoints.ModifiyTypeLibResult re = Actions.StatusPoints.ModifiyTypeLib(tl);
                    switch (re)
                    {
                        case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNull:
                            errmsg.Text = string.Format(this.TryFindResource("IsNull") as string, this.TryFindResource("TypeLib") as string);
                            break;
                        case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIDIsExist:
                            errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("TypeLibNum") as string);
                            break;
                        case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNotExist:
                            errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("TypeLib") as string);
                            break;
                        case Actions.StatusPoints.ModifiyTypeLibResult.OK:
                            errmsg.Text = this.TryFindResource("successfulupdate") as string;
                            this.typeLibList.ItemsSource = Config.TypeLibList = Data.DAL.TypeLib.List("");
                            typeLibList.Items.Refresh();
                            break;
                    }
                    ListStatusPoints(points);
                }

            }

        }

        void statusEdit_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (string.IsNullOrEmpty(statusByte.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusByte") as string); return; }
            if (string.IsNullOrEmpty(statusBit.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusBit") as string); return; }
            if (string.IsNullOrEmpty(statusName.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("StatusName") as string); return; }
            if (!statusByte.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("StatusByte") as string); return; }
            if (!statusBit.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("StatusBit") as string); return; }
            Data.Model.StatusPoints row = new Data.Model.StatusPoints();
            row.ID = (int)statusByte.Tag;
            row.StatusByte = statusByte.Text.Trim();
            row.StatusBit = statusBit.Text.Trim();
            row.LiftStatusNum = Convert.ToInt32(statusName.SelectedValue);

            Actions.StatusPoints.ModifiyStatusPointsResult ret = Actions.StatusPoints.ModifiyStatusPoints(row);
            switch (ret)
            {
                case Actions.StatusPoints.ModifiyStatusPointsResult.StatusPointsIsNull:
                    errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
                    break;
                case Actions.StatusPoints.ModifiyStatusPointsResult.StatusPointsIsNotExist:
                    errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
                    break;
                case Actions.StatusPoints.ModifiyStatusPointsResult.StatusPointsIsExist:
                    errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
                    break;
                case Actions.StatusPoints.ModifiyStatusPointsResult.OK:
                    errmsg.Text = this.TryFindResource("successfulupdate") as string;
                    Config.StatusPointsList = Data.DAL.StatusPoints.List("");
                    //ListStatusPoints();
                    statusByte.Text = "";
                    statusBit.Text = "";
                    statusName.Text = "";
                    break;
            }
        }

        void statusDelete_Click(object sender, RoutedEventArgs e)
        {
            List<int> ps = (from StatusPointsItem i in this.statusPointsList.Items
                             select i.ID).ToList();
            List<int> eps = (from StatusPointsItem i in this.statusPointsList.SelectedItems
                             select i.ID).ToList();
            int[] ids = (from int i in ps
                         where !eps.Exists(x => x == i)
                         select i).ToArray();
            Array.Sort(ids);
            Data.Model.TypeLib tl = Actions.StatusPoints.SelectTypeLib(typeLibNum.Text.Trim());
            if (null != tl)
            {
                tl.StatusPoints = ids.Join(",");
                Actions.StatusPoints.ModifiyTypeLibResult re = Actions.StatusPoints.ModifiyTypeLib(tl);
                switch (re)
                {
                    case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNull:
                        errmsg.Text = string.Format(this.TryFindResource("IsNull") as string, this.TryFindResource("TypeLib") as string);
                        break;
                    case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIDIsExist:
                        errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("TypeLibNum") as string);
                        break;
                    case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNotExist:
                        errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("TypeLib") as string);
                        break;
                    case Actions.StatusPoints.ModifiyTypeLibResult.OK:
                        errmsg.Text = this.TryFindResource("successfulupdate") as string;
                        this.typeLibList.ItemsSource = Config.TypeLibList = Data.DAL.TypeLib.List("");
                        typeLibList.Items.Refresh();
                        break;
                }
                ListStatusPoints(ids);
            }
            //int id = (int)statusByte.Tag;
            //Actions.StatusPoints.DeleteStatusPointsResult ret = Actions.StatusPoints.DeleteStatusPoints(id);
            //switch (ret)
            //{
            //    case Actions.StatusPoints.DeleteStatusPointsResult.StatusPointsIsNotExist:
            //        errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("LiftStatusPointsAdd") as string);
            //        break;
            //    case Actions.StatusPoints.DeleteStatusPointsResult.OK:
            //        errmsg.Text = this.TryFindResource("successfuldelete") as string;
            //        Config.StatusPointsList = Data.DAL.StatusPoints.List("");
            //        //ListStatusPoints();
            //        statusByte.Text = "";
            //        statusBit.Text = "";
            //        statusName.Text = "";
            //        break;
            //}
        }

        void statusPointsImport_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(typeLibNum.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("TypeLibNum") as string); return; }
            if (!typeLibNum.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("TypeLibNum") as string); return; }
            if (MessageBoxResult.Yes == MessageBox.Show(string.Format(this.TryFindResource("AskImportTypeLib") as string, typeLibNum.Text), this.TryFindResource("MessageBoxTitle") as string, MessageBoxButton.YesNo, MessageBoxImage.Question))
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Title = this.TryFindResource("ImportTitle") as string;
                dlg.Filter = this.TryFindResource("ImportFilter") as string;
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    string filename = dlg.FileName;
                    StreamReader sr = new StreamReader(filename, Encoding.Default); //File.OpenText(filename);
                    int lenok = 0, lenfail = 0;
                    string errstr = "";
                    string points = "";
                    while (!sr.EndOfStream)
                    {
                        string tmp = sr.ReadLine();
                        if (tmp.Length <= 4) { errstr += tmp + "；"; lenfail++; continue; }
                        string byt = tmp.Substring(0, 3);
                        string bit = tmp.Substring(3, 1);
                        string status = tmp.Substring(4, 4);
                        if (!byt.isNumeric()) { errstr += tmp + "；"; lenfail++; continue; }
                        if (!bit.isNumeric()) { errstr += tmp + "；"; lenfail++; continue; }
                        if (!status.isNumeric()) { errstr += tmp + "；"; lenfail++; continue; }

                        Data.Model.StatusPoints row = new Data.Model.StatusPoints();
                        row.StatusByte = byt;
                        row.StatusBit = bit;
                        row.LiftStatusNum = Convert.ToInt32(status);

                        Actions.StatusPoints.AddStatusPointsResult ret = Actions.StatusPoints.AddStatusPoints(row);

                        row = Actions.StatusPoints.SelectStatusPoints(byt, bit, Convert.ToInt32(status));
                        if (null != row) { points += row.ID + ","; lenok++; }
                        else { errstr += tmp + "；"; lenfail++; continue; }

                    }
                    Data.Model.TypeLib tl = new Data.Model.TypeLib();
                    tl.TypeLibNum = typeLibNum.Text.Trim();
                    tl.LiftType = liftType.SelectedIndex;
                    tl.StatusPoints = points;
                    Actions.StatusPoints.AddTypeLibResult tag = Actions.StatusPoints.ImportTypeLib(tl);
                    switch (tag)
                    {
                        case Actions.StatusPoints.AddTypeLibResult.TypeLibIsNull:
                            break;
                        case Actions.StatusPoints.AddTypeLibResult.OK:
                            this.typeLibList.ItemsSource = Data.DAL.TypeLib.List("");
                            typeLibList.Items.Refresh();
                            break;
                    }
                    errmsg.Text = string.Format(this.TryFindResource("ImportMsg") as string, lenok, lenfail, errstr);
                }
            }
        }

        void statusPointsAdd_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (string.IsNullOrEmpty(typeLibNum.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("TypeLibNum") as string); return; }
            if (!typeLibNum.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("TypeLibNum") as string); return; }

            Data.Model.TypeLib tl = new Data.Model.TypeLib();
            tl.TypeLibNum = typeLibNum.Text.Trim();
            tl.LiftType = liftType.SelectedIndex;
            tl.FloorFormat = floorFormat.SelectedIndex;
            int[] ids = (from StatusPointsItem i in this.statusPointsList.SelectedItems
                         select i.ID).ToArray();
            Array.Sort(ids);
            tl.StatusPoints = ids.Join(",");

            Actions.StatusPoints.AddTypeLibResult re = Actions.StatusPoints.AddTypeLib(tl);
            switch (re)
            {
                case Actions.StatusPoints.AddTypeLibResult.TypeLibIsNull:
                    errmsg.Text = string.Format(this.TryFindResource("IsNull") as string, this.TryFindResource("TypeLib") as string);
                    break;
                case Actions.StatusPoints.AddTypeLibResult.TypeLibIDIsExist:
                    errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("TypeLibNum") as string);
                    break;
                case Actions.StatusPoints.AddTypeLibResult.OK:
                    errmsg.Text = this.TryFindResource("successfuladd") as string;
                    this.typeLibList.ItemsSource = Config.TypeLibList = Data.DAL.TypeLib.List("");
                    typeLibList.Items.Refresh();
                    break;
            }

        }

        void statusPointsEdit_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (null == this.typeLibList.SelectedItem) { errmsg.Text = this.TryFindResource("SelectOne") as string; return; };
            if (string.IsNullOrEmpty(typeLibNum.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("TypeLibNum") as string); return; }
            if (!typeLibNum.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("TypeLibNum") as string); return; }

            Data.Model.TypeLib tl = this.typeLibList.SelectedItem as Data.Model.TypeLib;
            tl.TypeLibNum = typeLibNum.Text.Trim();
            tl.LiftType = liftType.SelectedIndex;
            tl.FloorFormat = floorFormat.SelectedIndex;
            int[] ids = (from StatusPointsItem i in this.statusPointsList.SelectedItems
                         select i.ID).ToArray();
            Array.Sort(ids);
            tl.StatusPoints = ids.Join(",");

            Actions.StatusPoints.ModifiyTypeLibResult re = Actions.StatusPoints.ModifiyTypeLib(tl);
            switch (re)
            {
                case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNull:
                    errmsg.Text = string.Format(this.TryFindResource("IsNull") as string, this.TryFindResource("TypeLib") as string);
                    break;
                case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIDIsExist:
                    errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("TypeLibNum") as string);
                    break;
                case Actions.StatusPoints.ModifiyTypeLibResult.TypeLibIsNotExist:
                    errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("TypeLib") as string);
                    break;
                case Actions.StatusPoints.ModifiyTypeLibResult.OK:
                    errmsg.Text = this.TryFindResource("successfulupdate") as string;
                    this.typeLibList.ItemsSource = Config.TypeLibList = Data.DAL.TypeLib.List("");
                    typeLibList.Items.Refresh();
                    break;
            }
        }

        void statusPointsDelete_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (this.typeLibList.SelectedItem == null) { errmsg.Text = this.TryFindResource("SelectOne") as string; return; }

            Data.Model.TypeLib tl = this.typeLibList.SelectedItem as Data.Model.TypeLib;

            Actions.StatusPoints.DeleteTypeLibResult re = Actions.StatusPoints.DeleteTypeLib(tl.ID);
            switch (re)
            {
                case Actions.StatusPoints.DeleteTypeLibResult.TypeLibIsNotExist:
                    errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("TypeLib") as string);
                    break;
                case Actions.StatusPoints.DeleteTypeLibResult.OK:
                    errmsg.Text = this.TryFindResource("successfuldelete") as string;
                    this.typeLibList.ItemsSource = Config.TypeLibList = Data.DAL.TypeLib.List("");
                    typeLibList.Items.Refresh();
                    break;
            }
        }


        private class StatusPointsItem
        {
            public int ID { get; set; }
            public string Byte { get; set; }
            public string Bit { get; set; }
            public int StatusNum { get; set; }
            public string StatusName { get; set; }
        }
    }

}
